#============================================================
#	Place Cell
#============================================================
#  替换瓷砖
#============================================================
# @datetime: 2022-3-15 08:39:47
#============================================================
extends Node


const Spring_Scn = preload("res://src/scene/env/tile/spring/Spring.tscn")
const Spikes_Scn = preload("res://src/scene/env/tile/spikes/Spikes.tscn")
const Stairs_Scn = preload("res://src/scene/env/tile/stairs/Stairs.tscn")
const Bridge_Scn = preload("res://src/scene/env/tile/bridge/Bridge.tscn")


## 关卡地图
onready var _level := get_parent() as TileMap
## 是否生成敌人
export var generate_enemy : bool = true


#============================================================
#   自定义
#============================================================
##  Add Node 
## @node  
func add_node(node: Node2D, pos: Vector2) -> void:
	node.global_position = pos
	_level.call_deferred("add_child", node)


##  替换瓦片
func replace_cell():
	yield(get_tree(), "idle_frame")
	if _level == null:
		_level = get_parent() as TileMap
	
	var pos : Vector2
	var TileType = MapData.TileType
	
	# 桥
	for cell in _level.get_used_cells_by_id(TileType.Bridge):
		pos = _level.map_to_world(cell)
		var coord : Vector2 = _level.get_cell_autotile_coord(cell.x, cell.y)
		_level.set_cellv(cell, -1)
		var bridge = Bridge_Scn.instance()
		bridge.global_position = pos
		_level.call_deferred("add_child", bridge)
		bridge.set_sprite_type(coord.x)
	
	# 弹簧
	for cell in _level.get_used_cells_by_id(TileType.Spring):
		pos = _level.map_to_world(cell)
		add_node(Spring_Scn.instance(), pos + Vector2(4, 4))
	
	# 尖刺
	for cell in _level.get_used_cells_by_id(TileType.Spikes):
		pos = _level.map_to_world(cell)
		add_node(Spikes_Scn.instance(), pos + Vector2(4, 6))
	
	# 楼梯
	for cell in _level.get_used_cells_by_id(TileType.Stairs):
		pos = _level.map_to_world(cell)
		# 增加功能，先扫描一遍在顶部的楼梯
		var node = Stairs_Scn.instance()
		node.global_position = pos
		_level.call_deferred("add_child", node)
	
	# 门
	var door_points = []
	for cell in _level.get_used_cells_by_id(TileType.Door):
		door_points.append(_level.map_to_world(cell))
	
	# 敌人
	for cell in _level.get_used_cells_by_id(TileType.Enemy):
		if generate_enemy:
			if randf() < 0.66:
				var list = [
#					preload("res://src/scene/role/enemy/slime/Slime.tscn"),
#					preload("res://src/scene/role/enemy/snake/Snake.tscn"),
#					preload("res://src/scene/role/enemy/mooseman/MooseMan.tscn"),
				]
#				var enemy : EnemyBase = MathUtil.rand_item(list).instance()
#				add_node(enemy, cell_pos_to_world(pos))
	
	


